import React, { useEffect, useState, useRef } from 'react';
import PropTypes from 'prop-types';
import { useHistory } from 'react-router-dom';

export default function RouterAnimate(WrapComponent) {
  // return React.Children.map(props.children, (child) => {
  //   return React.cloneElement(child, {
  //     routerAnimationIn: routerAnimation ? routerClass : '',
  //     getRef,
  //   });
  // });
  return (props) => {
    const { routerAnimation, customClass, animateTime } = props;
    const refChildren = useRef(null);

    const [routerClass, setRouterCalss] = useState(customClass || 'router-animate-in-before'); // 动画类名
    const routerTime = animateTime || 300; // 动画时长

    // 获取子组件dom
    const getRef = (dom) => {
      refChildren.current = dom;
    };

    useEffect(() => {
      // 设置进入动画
      requestAnimationFrame(() => {
        setRouterCalss('router-animate-in-after');
      });
      // 清除动画css类名
      setTimeout(() => {
        setRouterCalss('');
      }, routerTime);

      // 组件卸载前执行
      return () => {
        // 卸载前将dom保留，等动画结束再完全卸载
        const rect = refChildren.current.dom.getBoundingClientRect();
        refChildren.current.dom.style.position = 'absolute';
        refChildren.current.dom.style.left = rect.left + 'px';
        refChildren.current.dom.style.top = rect.top + 'px';
        refChildren.current.dom.style.transition = `transform ${routerTime / 1000}s`;
        refChildren.current.parentDom.appendChild(refChildren.current.dom);
        requestAnimationFrame(() => {
          refChildren.current.dom.style.transform = 'translateX(100%)';
          // refChildren.current.dom.style.transformOrigin = 'right center';
        });

        setTimeout(() => {
          refChildren.current.parentDom.removeChild(refChildren.current.dom);
          refChildren.current = null;
        }, routerTime);
      };
    }, []);

    return (
      <WrapComponent
        {...props}
        routerAnimationIn={routerAnimation ? routerClass : ''}
        getRef={getRef}
      ></WrapComponent>
    );
  };
}

// RouterAnimate.propTypes = {
//   routerAnimation: PropTypes.bool, // 是否需要路由动画
//   animateTime: PropTypes.number, // 动画时长
//   customClass: PropTypes.string, // 自定义动画类名
// };
